/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.ufpr.tads.suck.Controller;

import br.ufpr.tads.suck.model.Agendamento;
import br.ufpr.tads.suck.model.AgendamentoDAO;
import br.ufpr.tads.suck.model.AvisoException;
import br.ufpr.tads.suck.model.PessoaDao;
import br.ufpr.tads.suck.model.Pessoa;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 *
 * @author VictorHugo
 */
@WebServlet(name = "AgendamentoServ", urlPatterns = {"/AgendamentoServ"})
public class AgendamentoServ extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileNotFoundException, ClassNotFoundException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            String metodo = request.getParameter("action");
            
            try {
                AgendamentoDAO agendamento = new AgendamentoDAO();
                if (metodo.equalsIgnoreCase("obter")) {
                    Agendamento agenda = agendamento.agendamento();

                    JSONObject obj = new JSONObject();
                    obj.put("paciente", agenda.getPaciente().getNome());
                    obj.put("anamnese", agenda.getAnamnese());
                    obj.put("id", agenda.getId());
                    out.println(obj);
                } else if (metodo.equalsIgnoreCase("search")) {
                    String cpf = request.getParameter("cpf").replaceAll("\\D", "");
                    List<Pessoa> pessoas = new PessoaDao().listPessoa(cpf, "_nome_", "Paciente", -1, -1);
                    if(pessoas.isEmpty()){
                        JSONObject obj = new JSONObject();
                        //obj.put("Erro:", "");
                        //obj.put("id", );
                        out.println(obj);
                    }
                    Pessoa p = pessoas.get(0);

                    //Agendamento agenda = agendamento.agendamentoPaciente(p.getId());
                    //List<Agendamento> lista = agendamento.agendamentoPaciente(p);
                    JSONArray list = new JSONArray();
                    String pNome = p.getNome();
                    for (Agendamento agenda : agendamento.agendamentoPaciente(p)) {
                        JSONObject obj = new JSONObject();
                        obj.put("id", agenda.getId());
                        obj.put("paciente", pNome);
                        obj.put("anamnese", agenda.getAnamnese());
                        obj.put("estado", agenda.getEstado());
                        obj.put("situacao", agenda.getSituacao());
                        obj.put("medico", agenda.getMedico().getNome());
                        list.add(obj);
                    }
                    out.println(list);
                }if (metodo.equalsIgnoreCase("up")) {
                    System.out.println(metodo);
                    System.out.println("id"+request.getParameter("ida"));
                    Agendamento ag = new Agendamento();
                    ag.setDiagnostico(request.getParameter("diagnostico"));
                    ag.setReceita(request.getParameter("receita"));
                    ag.setId(Integer.parseInt(request.getParameter("ida")));
                    //ag.getMedico().setId(1);
                    agendamento.upAgenda(ag);
                    
                }
                
            } catch (AvisoException ex) {
                JSONObject e = new JSONObject();

                e.put("erro", ex.getMessage());
                out.println(e);
                System.out.println(e);

            } catch (NumberFormatException e) {
                JSONObject er = new JSONObject();
                er.put("erro", "Campo Numerico " + e.getMessage());
                out.println(er);
                System.out.println(e);
            }

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileNotFoundException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AgendamentoServ.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(AgendamentoServ.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileNotFoundException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AgendamentoServ.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(AgendamentoServ.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
